<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>调用链详情</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }
        
        .header {
            background: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            color: #2c3e50;
            font-size: 24px;
        }
        
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-block;
            transition: background-color 0.2s;
        }
        
        .btn-secondary {
            background-color: #95a5a6;
            color: white;
        }
        
        .btn-secondary:hover {
            background-color: #7f8c8d;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .api-summary {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .api-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .api-method {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: bold;
            color: white;
            margin-right: 10px;
        }
        
        .method-GET { background-color: #27ae60; }
        .method-POST { background-color: #3498db; }
        .method-PUT { background-color: #f39c12; }
        .method-DELETE { background-color: #e74c3c; }
        
        .status-badge {
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: bold;
        }
        
        .status-success {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-error {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .api-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            font-size: 14px;
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
        }
        
        .info-label {
            font-weight: 500;
            color: #666;
            margin-bottom: 4px;
        }
        
        .info-value {
            color: #333;
        }
        
        .trace-tree {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .tree-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            font-weight: 500;
        }
        
        .tree-content {
            padding: 20px;
        }
        
        .tree-node {
            margin-bottom: 10px;
        }
        
        .node-content {
            display: flex;
            align-items: center;
            padding: 12px;
            border: 1px solid #eee;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .node-content:hover {
            background-color: #f8f9fa;
            border-color: #3498db;
        }
        
        .node-content.expanded {
            background-color: #e3f2fd;
            border-color: #2196f3;
        }
        
        .node-indent {
            width: 20px;
            height: 1px;
            display: inline-block;
        }
        
        .node-icon {
            width: 16px;
            height: 16px;
            margin-right: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }
        
        .node-type-api {
            background-color: #3498db;
            color: white;
            border-radius: 3px;
        }
        
        .node-type-method {
            background-color: #95a5a6;
            color: white;
            border-radius: 50%;
        }
        
        .node-info {
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .node-name {
            font-weight: 500;
            color: #2c3e50;
        }
        
        .node-method {
            font-size: 12px;
            color: #666;
            margin-left: 8px;
        }
        
        .node-stats {
            display: flex;
            align-items: center;
            gap: 15px;
            font-size: 12px;
            color: #666;
        }
        
        .node-duration {
            font-weight: 500;
        }
        
        .node-status {
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: bold;
        }
        
        .node-details {
            margin-top: 10px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 6px;
            display: none;
        }
        
        .node-details.show {
            display: block;
        }
        
        .details-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .detail-section {
            background: white;
            padding: 12px;
            border-radius: 4px;
            border: 1px solid #eee;
        }
        
        .detail-title {
            font-weight: 500;
            margin-bottom: 8px;
            color: #2c3e50;
        }
        
        .detail-content {
            font-size: 13px;
            color: #666;
        }
        
        .json-content {
            background: #2c3e50;
            color: #ecf0f1;
            padding: 10px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            overflow-x: auto;
            white-space: pre-wrap;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .error {
            text-align: center;
            padding: 40px;
            color: #e74c3c;
        }
        
        .children {
            margin-left: 0;
            margin-top: 5px;
        }
        
        .tree-line {
            display: inline-block;
            width: 24px;
            height: 20px;
            position: relative;
            margin-right: 4px;
        }
        
        .tree-line::before {
            content: '';
            position: absolute;
            left: 50%;
            top: 0;
            bottom: 0;
            width: 1px;
            background-color: #ddd;
        }
        
        .expand-icon {
            display: inline-block;
            width: 16px;
            height: 16px;
            text-align: center;
            line-height: 16px;
            font-size: 10px;
            cursor: pointer;
            margin-right: 8px;
            color: #666;
            transition: transform 0.2s;
        }
        
        .expand-icon:hover {
            color: #333;
        }
        
        .expand-icon.collapsed {
            transform: rotate(-90deg);
        }
        
        .expand-icon-placeholder {
            display: inline-block;
            width: 16px;
            height: 16px;
            margin-right: 8px;
        }
        
        .node-level {
            display: inline-block;
            background-color: #f0f0f0;
            color: #666;
            padding: 1px 6px;
            border-radius: 10px;
            font-size: 10px;
            margin-left: 8px;
        }
        
        .children.collapsed {
            display: none;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <h1>调用链详情</h1>
            <a href="/chain-trace" class="btn btn-secondary">返回列表</a>
        </div>
    </div>
    
    <div class="container">
        <!-- API概要信息 -->
        <div class="api-summary" id="apiSummary" style="display: none;">
            <!-- 动态生成 -->
        </div>
        
        <!-- 调用链树 -->
        <div class="trace-tree">
            <div class="tree-header">
                <span>调用链路图</span>
                <div style="float: right;">
                    <button class="btn btn-secondary" onclick="expandAll()" style="margin-right: 10px;">展开全部</button>
                    <button class="btn btn-secondary" onclick="collapseAll()">折叠全部</button>
                </div>
            </div>
            <div class="tree-content" id="treeContent">
                <div class="loading">加载中...</div>
            </div>
        </div>
    </div>
    
    <script th:inline="javascript">
        const rootId = /*[[${rootId}]]*/ '';
        let traceData = null;
        
        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', function() {
            loadTraceData();
        });
        
        // 加载调用链数据
        function loadTraceData() {
            fetch(`/chain-trace/api/${rootId}/trace`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('API not found');
                    }
                    return response.json();
                })
                .then(data => {
                    traceData = data;
                    renderApiSummary(data);
                    renderTraceTree(data);
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('treeContent').innerHTML = '<div class="error">加载失败：' + error.message + '</div>';
                });
        }
        
        // 渲染API概要信息
        function renderApiSummary(data) {
            const summaryElement = document.getElementById('apiSummary');
            
            const html = `
                <div class="api-header">
                    <div>
                        <span class="api-method method-${data.httpMethod}">${data.httpMethod}</span>
                        <span style="font-size: 18px; font-weight: 500;">${data.url}</span>
                    </div>
                    <div>
                        <span class="status-badge ${data.success ? 'status-success' : 'status-error'}">
                            ${data.success ? '成功' : '失败'}
                        </span>
                    </div>
                </div>
                <div class="api-info">
                    <div class="info-item">
                        <div class="info-label">开始时间</div>
                        <div class="info-value">${formatTime(data.startTime)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">结束时间</div>
                        <div class="info-value">${formatTime(data.endTime)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">总耗时</div>
                        <div class="info-value">${data.duration}ms</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">客户端IP</div>
                        <div class="info-value">${data.clientIp || '-'}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">模块</div>
                        <div class="info-value">${data.module || '-'}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">操作</div>
                        <div class="info-value">${data.name || '-'}</div>
                    </div>
                </div>
            `;
            
            summaryElement.innerHTML = html;
            summaryElement.style.display = 'block';
        }
        
        // 渲染调用链树
        function renderTraceTree(data) {
            const treeElement = document.getElementById('treeContent');
            treeElement.innerHTML = renderTreeNode(data, 0);
        }
        
        // 渲染树节点
        function renderTreeNode(node, level) {
            const nodeId = 'node-' + node.id;
            const detailsId = 'details-' + node.id;
            
            // 计算缩进和连接线
            let indentHtml = '';
            for (let i = 0; i < level; i++) {
                indentHtml += '<span class="tree-line"></span>';
            }
            
            // 展开/折叠图标
            const hasChildren = node.children && node.children.length > 0;
            const expandIcon = hasChildren ? 
                `<span class="expand-icon" onclick="toggleChildren('${nodeId}', this, event)">▼</span>` : 
                '<span class="expand-icon-placeholder"></span>';
            
            let html = `
                <div class="tree-node" id="${nodeId}">
                    <div class="node-content" onclick="toggleNodeDetails('${detailsId}', this)">
                        ${indentHtml}
                        ${expandIcon}
                        <div class="node-icon node-type-${node.type}">
                            ${node.type === 'api' ? 'API' : 'M'}
                        </div>
                        <div class="node-info">
                            <div>
                                <span class="node-name">${node.name}</span>
                                <span class="node-method">${node.method}</span>
                                <span class="node-level">L${node.level}</span>
                            </div>
                            <div class="node-stats">
                                <span class="node-duration">${node.duration}ms</span>
                                <span class="node-status ${node.success ? 'status-success' : 'status-error'}">
                                    ${node.success ? '成功' : '失败'}
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="node-details" id="${detailsId}">
                        ${renderNodeDetails(node)}
                    </div>
            `;
            
            // 渲染子节点
            if (hasChildren) {
                html += '<div class="children" id="children-' + node.id + '">';
                for (const child of node.children) {
                    html += renderTreeNode(child, level + 1);
                }
                html += '</div>';
            }
            
            html += '</div>';
            return html;
        }
        
        // 渲染节点详情
        function renderNodeDetails(node) {
            let html = '<div class="details-grid">';
            
            // 基本信息
            html += `
                <div class="detail-section">
                    <div class="detail-title">基本信息</div>
                    <div class="detail-content">
                        <div><strong>ID:</strong> ${node.id}</div>
                        <div><strong>类名:</strong> ${node.className}</div>
                        <div><strong>方法:</strong> ${node.method}</div>
                        <div><strong>层级:</strong> ${node.level}</div>
                        ${node.description ? `<div><strong>描述:</strong> ${node.description}</div>` : ''}
                    </div>
                </div>
            `;
            
            // 时间信息
            html += `
                <div class="detail-section">
                    <div class="detail-title">时间信息</div>
                    <div class="detail-content">
                        <div><strong>开始:</strong> ${formatTime(node.startTime)}</div>
                        <div><strong>结束:</strong> ${formatTime(node.endTime)}</div>
                        <div><strong>耗时:</strong> ${node.duration}ms</div>
                    </div>
                </div>
            `;
            
            // API特有信息
            if (node.type === 'api') {
                html += `
                    <div class="detail-section">
                        <div class="detail-title">请求信息</div>
                        <div class="detail-content">
                            <div><strong>URL:</strong> ${node.url}</div>
                            <div><strong>方法:</strong> ${node.httpMethod}</div>
                            <div><strong>客户端IP:</strong> ${node.clientIp || '-'}</div>
                            <div><strong>模块:</strong> ${node.module || '-'}</div>
                        </div>
                    </div>
                `;
            }
            
            html += '</div>';
            
            // 参数信息
            if (node.params && Object.keys(node.params).length > 0) {
                html += `
                    <div class="detail-section">
                        <div class="detail-title">请求参数</div>
                        <div class="json-content">${JSON.stringify(node.params, null, 2)}</div>
                    </div>
                `;
            }
            
            // 返回值
            if (node.result) {
                html += `
                    <div class="detail-section">
                        <div class="detail-title">返回值</div>
                        <div class="json-content">${JSON.stringify(node.result, null, 2)}</div>
                    </div>
                `;
            }
            
            // 异常信息
            if (node.exceptionInfo) {
                html += `
                    <div class="detail-section">
                        <div class="detail-title">异常信息</div>
                        <div class="json-content">${node.exceptionInfo}</div>
                    </div>
                `;
            }
            
            // 自定义参数
            if (node.customs && Object.keys(node.customs).length > 0) {
                html += `
                    <div class="detail-section">
                        <div class="detail-title">自定义参数</div>
                        <div class="json-content">${JSON.stringify(node.customs, null, 2)}</div>
                    </div>
                `;
            }
            
            return html;
        }
        
        // 切换节点详情显示
        function toggleNodeDetails(detailsId, nodeElement) {
            const detailsElement = document.getElementById(detailsId);
            
            if (detailsElement.classList.contains('show')) {
                detailsElement.classList.remove('show');
                nodeElement.classList.remove('expanded');
            } else {
                detailsElement.classList.add('show');
                nodeElement.classList.add('expanded');
            }
        }
        
        // 切换子节点显示/隐藏
        function toggleChildren(nodeId, iconElement, event) {
            event.stopPropagation(); // 阻止事件冒泡
            
            const childrenElement = document.getElementById('children-' + nodeId.replace('node-', ''));
            
            if (childrenElement.classList.contains('collapsed')) {
                childrenElement.classList.remove('collapsed');
                iconElement.classList.remove('collapsed');
                iconElement.textContent = '▼';
            } else {
                childrenElement.classList.add('collapsed');
                iconElement.classList.add('collapsed');
                iconElement.textContent = '▶';
            }
        }
        
        // 展开所有节点
        function expandAll() {
            document.querySelectorAll('.children.collapsed').forEach(element => {
                element.classList.remove('collapsed');
            });
            document.querySelectorAll('.expand-icon.collapsed').forEach(element => {
                element.classList.remove('collapsed');
                element.textContent = '▼';
            });
        }
        
        // 折叠所有节点
        function collapseAll() {
            document.querySelectorAll('.children').forEach(element => {
                element.classList.add('collapsed');
            });
            document.querySelectorAll('.expand-icon').forEach(element => {
                if (element.textContent === '▼') {
                    element.classList.add('collapsed');
                    element.textContent = '▶';
                }
            });
        }
        
        // 格式化时间
        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleString('zh-CN');
        }
    </script>
</body>
</html>